import kurento from 'kurento-client';
import { RequestMethod } from "../lib/defines";
import { MemberBase, RoomBase } from "../utils/types";

export type IceQuery = {
  // 所属用户
  member: MemberBase;
  // 所属房间
  room: RoomBase;
  // ice
  iceCandidate: any;
}

export default function dissolve (app) {
  const { socket, rooms } = app.locals;
  const { userId } = socket.handshake.query;
  /**
   * 交换 ICE
   */
  socket.on(RequestMethod.iceCandidate, function({ room, iceCandidate, member }: IceQuery, cb?) {
    if (!room) return;
    const __room = rooms[room.classId]

    if (!__room) {
      return cb && cb({status: 'error', message: 'room not find!'})
    }

    const __member = __room.members[member.userId];

    if (!__member) {
      return cb && cb({status: 'error', message: 'member not find!'})
    }

    const __iceCandidate = kurento.getComplexType('IceCandidate')(iceCandidate);
    const endpoint = __member.getEndpoint(userId)

    if (endpoint) {
      endpoint.addIceCandidate(__iceCandidate).then(cb);
    } else {
      __member.candidatesQueue[userId]
      || (__member.candidatesQueue[userId] = [])

      __member.candidatesQueue[userId].push(__iceCandidate)
    }
  })
}
